package org.yuezejian.alarm.netty.channel.pool;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.yuezejian.alarm.netty.channel.WebsocketCustomChannelInitializer;
import org.yuezejian.alarm.netty.enums.ClientType;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * websocket通道池，用于管理和分配netty通道
 *
 * @author yuezejian
 * @since 2024.8.1
 */
@Slf4j
public class WebSocketChannelPool extends AbstractChannelPool {
    public WebSocketChannelPool(String host, int port, WebsocketCustomChannelInitializer initializer) {
        super(host, port, null, null, initializer);
        this.wsInitializer.setClientType(ClientType.WEBSOCKET); // 设置协议类型为 websocket
    }

    @Override
    protected Channel createNewChannel() throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(wsInitializer);
        log.info("WebSocket group:" + JSON.toJSONString(group));
        return bootstrap.connect(host, port).sync().channel();
    }
}
